/**
 * Copyright (C), 1968-2019, 美的集团股份有限公司
 * FileName: TreeUtil
 * Author:   fanyl5
 * Date:     2019/4/20 14:45
 * Description: 结构树工具
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.ruiysoft.crm.util;

import com.ruiysoft.crm.model.entity.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 结构树工具
 * @author: fanyl5
 * @date: 2019/4/20 14:45
 * @version: 1.0.0
 */
public class TreeUtil {

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
